package com.lnj.community.controller;


import com.alibaba.fastjson.JSONObject;
import com.lnj.community.dao.entity.Message;
import com.lnj.community.dao.entity.Page;
import com.lnj.community.dao.entity.User;
import com.lnj.community.dao.vo.MessageVo;
import com.lnj.community.dao.vo.NoticesVo;
import com.lnj.community.service.MessageService;
import com.lnj.community.service.UserService;
import com.lnj.community.utiles.CommunityUtil;
import com.lnj.community.utiles.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

import static com.lnj.community.utiles.CommunityConstant.*;

@Controller
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    // 私信列表
    @RequestMapping(path = "/letter/list", method = RequestMethod.GET)
    public String getLetterList(Model model, Page page) {
        User user = HostHolder.getUser();
        // 分页信息
        page.setLimit(5);
        page.setPath("/letter/list");
        // 会话数量
        page.setRows(messageService.findConversationCount(user.getId()));

        // 会话列表
        List<Message> conversationList = messageService.findConversations(
                user.getId(), page.getOffset(), page.getLimit());
        // 会话列表中的每个会话都需要包含未读消息数量和会话目标用户
        //一个Map对象用于存储每个会话的信息，包括会话对象、未读消息数量和会话目标用户。
        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", message);
                map.put("letterCount", messageService.findLetterCount(message.getConversationId()));
                map.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target", userService.findUserById(targetId));

                conversations.add(map);
            }
        }
        model.addAttribute("conversations", conversations);

        // 查询未读消息数量 (所有会话的未读消息数量)
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        // 查询未读通知数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(null, user.getId());
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "/site/letter";
    }

    // 私信详情
    @RequestMapping(path = "/letter/detail/{conversationId}", method = RequestMethod.GET)
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model) {
        // 分页信息
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.findLetterCount(conversationId));

        // 私信列表
        List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());
        // 私信列表中的每个私信都需要包含发送者和接收者的信息
        List<Map<String, Object>> letters = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.findUserById(message.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters", letters);

        // 私信目标
        model.addAttribute("target", getLetterTarget(conversationId));

        //获取未读消息的ID列表
        List<Integer> ids = getLetterUnreadIds(letterList);
        if (!ids.isEmpty()) {
            // 批量更新未读消息的状态
            messageService.readMessage(ids);
        }

        return "/site/letter-detail";
    }

    // 发送私信
    @RequestMapping(path = "/letter/send", method = RequestMethod.POST)
    @ResponseBody
    public String sendLetter(String toName, String content) {
        User target = userService.findUserByName(toName);
        if (target == null) {
            return CommunityUtil.getJSONString(1, "目标用户不存在!");
        }
        Message message = new Message();
        message.setFromId(HostHolder.getUser().getId());
        message.setToId(target.getId());
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setStatus(0);
        message.setCreateTime(new Date());
        messageService.addMessage(message);
        return CommunityUtil.getJSONString(0);
    }

    /**
     * 根据会话id获取会话目标用户
     * @param conversationId 会话id
     * @return
     */
    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (HostHolder.getUser().getId() == id0) {
            return userService.findUserById(id1);
        } else {
            return userService.findUserById(id0);
        }
    }
    /**
     * 获取未读消息的ID列表
     * @return
     */
    private List<Integer> getLetterUnreadIds(List<Message> conversationList) {
       List<Integer> ids = new ArrayList<>();
        if (conversationList!= null) {
            // 遍历会话列表的每个消息
            for (Message message : conversationList) {
                // 如果当前用户是消息的接收者，并且消息的状态是未读
                if (HostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }

    @RequestMapping(path = "/notice/list", method = RequestMethod.GET)
    public String getNoticeList(Model model) {
        // 获取当前用户
        User user = HostHolder.getUser();
        // 查询评论类通知
        Message message = messageService.findLatestNotice( TOPIC_COMMENT,user.getId());
        MessageVo messageVO = new MessageVo();
        if (message != null) {
            messageVO.setMessage(message);
            //把内容中的转义字符还原为字符串
            String content = HtmlUtils.htmlUnescape(message.getContent());
            //把字符串解析为Map对象
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.setUser(userService.findUserById((Integer) data.get("userId")));
            messageVO.setEntityType((Integer) data.get("entityType"));
            messageVO.setEntityId((Integer) data.get("entityId"));
            messageVO.setPostId((Integer)data.get("postId"));

            //获取该通知类型的总数量和未读数量
            int count = messageService.findNoticeCount( TOPIC_COMMENT,user.getId());
            messageVO.setCount( count);
            int unread = messageService.findNoticeUnreadCount( TOPIC_COMMENT,user.getId());
            messageVO.setUnread(unread);
        }
        model.addAttribute("commentNotice", messageVO);

        // 查询点赞类通知
        message = messageService.findLatestNotice( TOPIC_LIKE,user.getId());
        messageVO = new MessageVo();
        if (message != null) {
            messageVO.setMessage(message);
            //把内容中的转义字符还原为字符串
            String content = HtmlUtils.htmlUnescape(message.getContent());
            //把字符串解析为Map对象
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.setUser(userService.findUserById((Integer) data.get("userId")));
            messageVO.setEntityType((Integer) data.get("entityType"));
            messageVO.setEntityId((Integer) data.get("entityId"));
            messageVO.setPostId((Integer)data.get("postId"));

            //获取该通知类型的总数量和未读数量
            int count = messageService.findNoticeCount( TOPIC_LIKE,user.getId());
            messageVO.setCount( count);
            int unread = messageService.findNoticeUnreadCount(TOPIC_LIKE,user.getId());
            messageVO.setUnread(unread);
        }
        model.addAttribute("likeNotice", messageVO);

        // 查询关注类通知
        message = messageService.findLatestNotice( TOPIC_FOLLOW,user.getId());
        messageVO = new MessageVo();
        if (message != null) {
            messageVO.setMessage(message);
            //把内容中的转义字符还原为字符串
            String content = HtmlUtils.htmlUnescape(message.getContent());
            //把字符串解析为Map对象
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            //根据用户id查询用户信息 存到messageVO中
            messageVO.setUser(userService.findUserById((Integer) data.get("userId")));
            //把实体类型和实体id存到messageVO中
            messageVO.setEntityType((Integer) data.get("entityType"));
            messageVO.setEntityId((Integer) data.get("entityId"));

            //获取该通知类型的总数量和未读数量
            int count = messageService.findNoticeCount( TOPIC_FOLLOW ,user.getId());
            messageVO.setCount( count);
            int unread = messageService.findNoticeUnreadCount(TOPIC_FOLLOW ,user.getId());
            messageVO.setUnread(unread);
        }
        model.addAttribute("followNotice", messageVO);

        // 查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        // 查询未读通知数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(null, user.getId());
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "/site/notice";
    }

    @RequestMapping(path = "/notice/detail/{topic}", method = RequestMethod.GET)
    public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model) {
        User user = HostHolder.getUser();

        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(topic,user.getId()));

        // 通知列表 获取当前主题的通知列表
        List<Message> noticeList = messageService.findNotices(topic,user.getId(), page.getOffset(), page.getLimit());
        List<NoticesVo> noticeVoList = new ArrayList<>();
        if (noticeList != null) {
            for (Message notice : noticeList) {
               NoticesVo noticesVo = new NoticesVo();
                // 通知
                noticesVo.setNotice( notice);
                // 内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                noticesVo.setUser( userService.findUserById((Integer) data.get("userId")));
                noticesVo.setEntityType((Integer) data.get("entityType"));
                noticesVo.setEntityId((Integer) data.get("entityId"));
                if (data.containsKey("postId")) {
                    noticesVo.setPostId((Integer) data.get("postId"));
                }

                // 通知作者
                noticesVo.setFromUser(userService.findUserById(notice.getFromId()));

                noticeVoList.add(noticesVo);
            }
        }
        model.addAttribute("notices", noticeVoList);

        // 设置已读
        List<Integer> ids = getLetterUnreadIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }

        return "/site/notice-detail";
    }

}
